/**
 * Created by lcj08996 on 2016/7/15.
 * 抢购倒计时组件
 * new TimeDown({
    startTime:starTime,     抢购开始时间毫秒数
    endTime:endTime,        抢购结束时间毫秒数
    nowTime:nowTime,        当前时间毫秒数
    renderCountDown:function(down_second,day,hour,minute,second,status){
        //down_second   总共剩余倒计时秒数
        //status    0,1,2 分别表示 抢购未开始，抢购中，抢购结束
        //console.log(day + "天" + hour + ":" + minute + ":" + second + "当前状态：" + status);
    }
});
 *
 */
(function(){

    /**
     * 倒计时效果
     * @param  {number} end   结束时间毫秒形式
     * @param  {number} start 开始时间毫秒形式
     * @return {[type]}       [description]
     */
    function TimeDown(option) {

        this.startTime = option.startTime;
        this.endTime = option.endTime;
        this.nowTime = option.nowTime;
        this.renderCountDown = option.renderCountDown;

        var downTime = 0;
        if(this.nowTime < this.startTime){
            this.status = 0;
            downTime = this.startTime - this.nowTime;
        }else if(this.nowTime >= this.startTime&&this.nowTime < this.endTime){
            this.status = 1;
            downTime = this.endTime - this.nowTime;
        }else{
            this.status = 2;
            downTime = 0;
        }
        this.countDown(downTime);
    }

    TimeDown.prototype = {
        status:0,   //0 未开始， 1 抢购中, 2 抢购结束
        startTime:0,
        endTime:0,
        nowTime:0,
        timer: null,
        countDown: function(downTime){
            var that = this;

            //如果直接抢购结束 不进入定时器 直接回调结束
            if(that.status >= 2){
                that.renderCountDown(0,0,0,0,0,2);
                return;
            }
            var down_second = downTime/1000;
            that.timer = setInterval(function(){
                //这边改了下，还剩1s的时候就执行下一个状态该执行的
                if (down_second > 1) {

                    var day = Math.floor((down_second / 3600) / 24);
                    var hour = Math.floor((down_second / 3600) % 24);
                    var minute = Math.floor((down_second / 60) % 60);
                    var second = Math.floor(down_second % 60);
                    that.renderCountDown(down_second,day,hour,minute,second,that.status);

                    down_second--;

                } else {
                    clearInterval(that.timer);
                    //执行抢购中倒计时
                    that.status++;
                    //抢购中
                    if(that.status == 1){
                        that.countDown(that.endTime - that.startTime);
                    }else if(that.status >= 2){
                        that.renderCountDown(0,0,0,0,0,2);
                    }
                }
            },1000);
        }
    };

    module.exports = TimeDown;

})();
